"use client";
import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import Image from "next/image";
import { Drawer, Menu } from "antd";
import { MenuOutlined } from "@ant-design/icons";
import SearchBar from "@/components/SearchBar";
import UserInfo from "@/components/UserInfo";
import { usePathname } from "next/navigation";

export default function Header() {
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [activeKey, setActiveKey] = useState("home");
  const [isSticky, setIsSticky] = useState(false);
  const headerRef = useRef(null);
  const pathname = usePathname();

  // 监听滚动事件
  useEffect(() => {
    const handleScroll = () => {
      if (headerRef.current) {
        const headerHeight = headerRef.current.offsetHeight;
        setIsSticky(window.scrollY > headerHeight / 2);
      }
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  // 根据当前路径设置活跃项
  useEffect(() => {
    const pathToKeyMap: Record<string, string> = {
      "/": "home",
      "/quality": "quality",
      "/inspection": "inspection",
      "/certification": "certification",
      "/standard": "standard",
      "/favorites": "favorites",
      "/login": "login",
    };

    const matchedKey = pathToKeyMap[pathname] || "home";
    setActiveKey(matchedKey);
  }, [pathname]);

  const navItems = [
    {
      key: "home",
      label: "首页",
      href: "/",
      className: "text-blue-600 hover:text-blue-800 font-medium",
    },
    {
      key: "quality",
      label: "质量科普",
      href: "/quality",
      className: "text-gray-700 hover:text-blue-600 transition-colors",
    },
    {
      key: "inspection",
      label: "检测项点",
      href: "/inspection",
      className: "text-gray-700 hover:text-blue-600 transition-colors",
    },
    {
      key: "certification",
      label: "认证申请",
      href: "/certification",
      className: "text-gray-700 hover:text-blue-600 transition-colors",
    },
    {
      key: "standard",
      label: "标准检索",
      href: "/standard",
      className: "text-gray-700 hover:text-blue-600 transition-colors",
    },
    {
      key: "favorites",
      label: "我的收藏",
      href: "/favorites",
      className: "text-gray-700 hover:text-blue-600 transition-colors",
    },
  ];

  const handleNavClick = (key: string) => {
    setActiveKey(key);
    if (drawerVisible) {
      setDrawerVisible(false);
    }
  };

  const getNavItemClass = (item: (typeof navItems)[0]) => {
    if (item.key === activeKey) {
      return "text-blue-600 font-medium relative";
    }
    return `${item.className} relative group`;
  };

  return (
    <>
      {/* 顶部占位元素，防止内容跳动 */}
      <div className="h-[180px] md:h-[155px]"></div>
      {/* 主头部 */}
      <header
        ref={headerRef}
        className={`bg-gradient-to-b from-[#F2F6FF] to-[#FFFFFF] shadow-md w-full transition-all duration-300 ease-in-out
          ${
            isSticky
              ? "fixed top-0 left-0 z-50 pt-2 pb-2 shadow-lg"
              : "absolute top-0 left-0 pt-4 pb-4"
          }`}
      >
        <div className="container mx-auto">
          {/* Logo和搜索区域 */}
          <div
            className={`flex flex-col items-center md:flex-row md:justify-between transition-all duration-300
            ${
              isSticky ? "h-0 opacity-0 overflow-hidden" : "h-auto opacity-100"
            }`}
          >
            <div className="w-full md:flex justify-start items-center">
              <button
                className="md:hidden justify-center p-2 rounded-md hover:bg-gray-100 transition-colors"
                onClick={() => setDrawerVisible(true)}
                aria-label="打开菜单"
              >
                <MenuOutlined
                  style={{
                    fontSize: "24px",
                    color: "#666",
                    margin: "0 20px 0 0",
                  }}
                />
              </button>
              <Link href="/" className="flex items-center mb-4 md:mb-0">
                <Image
                  src="/images/logo.png"
                  alt="网站 Logo"
                  priority
                  width={398}
                  height={70}
                  className="rounded-md w-auto h-[50px] md:h-[70px]"
                  style={{ width: "398px", height: "auto", maxWidth: "100%" }}
                />
              </Link>
            </div>
            <div className="flex items-center gap-2 md:items-center">
              <SearchBar
                width={400}
                targetPath="/products"
                placeholder="搜索产品或科普内容..."
                clearAfterSearch={true}
                ignoreUrlParams={true}
              />
              {/* 非吸顶状态下的用户信息 (桌面端) */}
              <div className="hidden md:flex ml-2">
                <UserInfo />
              </div>
            </div>
          </div>

          {/* 导航菜单区域 */}
          <nav
            className={`flex text-sm justify-between items-center w-full transition-all duration-300
            ${isSticky ? "mt-0" : "mt-4"}`}
          >
            <div className="w-full flex justify-between items-center">
              {/* 移动端菜单按钮 (吸顶时显示) */}
              {isSticky && (
                <button
                  className="md:hidden justify-center p-2 rounded-md hover:bg-gray-100 transition-colors"
                  onClick={() => setDrawerVisible(true)}
                  aria-label="打开菜单"
                >
                  <MenuOutlined
                    style={{
                      fontSize: "24px",
                      color: "#666",
                    }}
                  />
                </button>
              )}

              {/* 桌面导航 */}
              <div className="hidden md:flex justify-left flex-1">
                {navItems.map((item) => (
                  <Link
                    key={item.key}
                    href={item.href}
                    className={`${getNavItemClass(
                      item
                    )} transition-all duration-300 px-4 py-2 mx-1`}
                    onClick={() => handleNavClick(item.key)}
                  >
                    {item.label}
                    {item.key === activeKey && (
                      <span className="absolute -bottom-1 left-0 w-full h-0.5 bg-blue-600 rounded-full transform scale-x-100 transition-transform duration-300 origin-center" />
                    )}
                    {item.key !== activeKey && (
                      <span className="absolute -bottom-1 left-0 w-full h-0.5 bg-blue-600 rounded-full transform scale-x-0 transition-transform duration-300 origin-center group-hover:scale-x-100" />
                    )}
                  </Link>
                ))}
              </div>

              {isSticky && (
                <div className="hidden md:flex">
                  <UserInfo />
                </div>
              )}
            </div>
          </nav>
        </div>

        {/* 移动端抽屉菜单 */}
        <Drawer
          title="菜单"
          placement="left"
          onClose={() => setDrawerVisible(false)}
          open={drawerVisible}
          width={280}
          destroyOnClose
        >
          <div className="mb-4">
            <UserInfo />
          </div>
          <Menu
            mode="vertical"
            selectedKeys={[activeKey]}
            onClick={({ key }) => handleNavClick(key)}
            items={navItems.map((item) => ({
              key: item.key,
              label: <Link href={item.href}>{item.label}</Link>,
            }))}
          />
        </Drawer>
      </header>
    </>
  );
}
